package com.study.demo01.consumer;

import com.rabbitmq.client.Channel;
import com.study.demo01.config.ConfirmConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2023/12/20 20:45
 * 批量消费
 * 没有这个 参数https://blog.csdn.net/qq_39840681/article/details/122368999
 * <p>
 * # Ack 手动确认|如果配置了 批量，这个配置不会生效，因此要在代码中设置|https://blog.csdn.net/m912595719/article/details/83787486
 * spring.rabbitmq.listener.simple.acknowledge-mode=manual
 *
 * 批处理其他内容可以看这里 https://springdoc.cn/spring-amqp/#receiving-batch
 */
@Slf4j
@Component
public class BathConsumer {
    /**
     * 批量消费就使用 List<Message> 接收消息吧，否则会转换失败
     *
     * @param channel
     * @param message 批量消息
     */
    @RabbitListener(queues = ConfirmConfig.confirm_queue_name_b , containerFactory = "simpleRabbitListenerContainerFactory")
    //public void receiveConfirmMessage(List<String> listMsg, Channel channel, List<Message> message) {
    public void receiveConfirmMessage(List<Message> message, Channel channel) {
        log.info("接收到 confirm队列消息[{}-条]", message.size());
        for (Message msg : message) {
            //channel内按顺序自增
            long deliveryTag = msg.getMessageProperties().getDeliveryTag();
            log.info("消费消息[{}-{}]", deliveryTag, new String(msg.getBody()));
            try {
                //签收|序号,是否批量确认
                channel.basicAck(deliveryTag, false);
                //channel.basicNack(deliveryTag, false, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
